package cuiyt.juc.reflaction;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author cyt
 * @create 2020-04-20 9:23
 */
public class Test09 {
    // 通过反射创建对象， 并且操作属性和方法
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 通过反射来创建对象， 默认调用无参构造器, 无参构造必须为公有
        Class<?> name = Class.forName("reflaction.User");
        Object instance = name.newInstance();
        System.out.println(instance);


        Constructor<?>[] constructors = name.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        constructors = name.getDeclaredConstructors();

        for (Constructor<?> constructor : constructors) {

            System.out.println(constructor);
        }
        // 指定调用有参构造器
        Constructor<?> constructor = name.getDeclaredConstructor(Integer.class, String.class, Integer.class);
        Object c = constructor.newInstance(1, "c", 1);
        System.out.println(c);
        // 操作方法
        Object user = (User) name.newInstance();
        Method setName = name.getDeclaredMethod("setName", String.class);

        // 使用 invoke 表示激活的意思，后面带上参数
        setName.invoke(user,"cyt");
        System.out.println(user);

        // 操作属性, 需要开启权限
        Field field = name.getDeclaredField("name");

        field.setAccessible(true);
        field.set(user, "崔雨田");

        System.out.println(user);
    }
}
